<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="box-card">
          <div class="user-profile">
            <div class="avatar-container">
              <img :src="user.avatar || defaultAvatar" class="user-avatar">
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <el-button size="small" type="primary">更换头像</el-button>
              </el-upload>
            </div>
            <div class="info-container">
              <h3>{{ user.name }}</h3>
              <p>{{ user.position }}</p>
              <p>{{ user.departmentName }}</p>
            </div>
          </div>
          <div class="user-bio">
            <div class="user-info-item">
              <i class="el-icon-user"></i>
              <span>{{ user.username }}</span>
            </div>
            <div class="user-info-item">
              <i class="el-icon-mobile-phone"></i>
              <span>{{ user.phone }}</span>
            </div>
            <div class="user-info-item">
              <i class="el-icon-message"></i>
              <span>{{ user.email }}</span>
            </div>
            <div class="user-info-item">
              <i class="el-icon-date"></i>
              <span>加入时间: {{ formatDate(user.createTime) }}</span>
            </div>
          </div>
          <div class="user-actions">
            <el-button type="primary" @click="showChangePasswordDialog">修改密码</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息" name="basic">
              <el-form
                ref="userForm"
                :model="userForm"
                :rules="rules"
                label-width="100px"
              >
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="userForm.name" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="userForm.phone" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userForm.email" />
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio-group v-model="userForm.gender">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                    <el-radio :label="0">未知</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateUserInfo">保存</el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="登录记录" name="loginLog">
              <el-table
                v-loading="logLoading"
                :data="loginLogs"
                border
                style="width: 100%"
              >
                <el-table-column
                  prop="loginTime"
                  label="登录时间"
                  width="180"
                />
                <el-table-column
                  prop="ip"
                  label="IP地址"
                  width="150"
                />
                <el-table-column
                  prop="location"
                  label="登录地点"
                  width="150"
                />
                <el-table-column
                  prop="browser"
                  label="浏览器"
                />
                <el-table-column
                  prop="os"
                  label="操作系统"
                />
                <el-table-column
                  prop="status"
                  label="状态"
                  width="100"
                >
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                      {{ scope.row.status === 1 ? '成功' : '失败' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
              <div class="pagination-container">
                <el-pagination
                  background
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="logQuery.page"
                  :page-sizes="[10, 20, 30, 50]"
                  :page-size="logQuery.size"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="logTotal"
                />
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <change-password
      :visible.sync="changePasswordVisible"
      :user-id="user.id"
    />
  </div>
</template>

<script>
import { getUserById, updateUser } from '@/api/user'
import { getLoginLogs } from '@/api/log'
import ChangePassword from './components/ChangePassword'
import { formatDate } from '@/utils/index'

export default {
  name: 'UserProfile',
  components: {
    ChangePassword
  },
  data() {
    return {
      user: {},
      userForm: {
        id: undefined,
        name: '',
        phone: '',
        email: '',
        gender: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      },
      defaultAvatar: require('@/assets/avatar/default.jpg'),
      activeTab: 'basic',
      changePasswordVisible: false,
      loginLogs: [],
      logLoading: false,
      logQuery: {
        page: 1,
        size: 10,
        userId: undefined
      },
      logTotal: 0
    }
  },
  created() {
    this.fetchUserInfo()
  },
  methods: {
    formatDate,
    fetchUserInfo() {
      // 实际项目中应该从store中获取当前用户ID或从后端获取当前登录用户信息
      const userId = this.$store.getters.userId || 1
      getUserById(userId).then(response => {
        this.user = response.data
        this.userForm = {
          id: this.user.id,
          name: this.user.name,
          phone: this.user.phone,
          email: this.user.email,
          gender: this.user.gender
        }
        this.logQuery.userId = this.user.id
        this.fetchLoginLogs()
      })
    },
    fetchLoginLogs() {
      this.logLoading = true
      getLoginLogs(this.logQuery).then(response => {
        this.loginLogs = response.data.records
        this.logTotal = response.data.total
        this.logLoading = false
      }).catch(() => {
        this.logLoading = false
      })
    },
    handleSizeChange(val) {
      this.logQuery.size = val
      this.fetchLoginLogs()
    },
    handleCurrentChange(val) {
      this.logQuery.page = val
      this.fetchLoginLogs()
    },
    updateUserInfo() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          const data = {
            ...this.userForm
          }
          updateUser(data).then(() => {
            this.$notify({
              title: '成功',
              message: '个人信息更新成功',
              type: 'success',
              duration: 2000
            })
            this.fetchUserInfo()
          })
        }
      })
    },
    resetForm() {
      this.userForm = {
        id: this.user.id,
        name: this.user.name,
        phone: this.user.phone,
        email: this.user.email,
        gender: this.user.gender
      }
    },
    showChangePasswordDialog() {
      this.changePasswordVisible = true
    },
    handleAvatarSuccess(res) {
      // 头像上传成功后的处理
      if (res.code === 200) {
        this.user.avatar = res.data
        // 更新用户头像
        updateUser({
          id: this.user.id,
          avatar: res.data
        }).then(() => {
          this.$notify({
            title: '成功',
            message: '头像更新成功',
            type: 'success',
            duration: 2000
          })
        })
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped>
.user-profile {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}
.avatar-container {
  margin-bottom: 20px;
  text-align: center;
}
.user-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: block;
  margin-bottom: 10px;
}
.info-container {
  text-align: center;
}
.info-container h3 {
  margin-top: 0;
  margin-bottom: 5px;
}
.info-container p {
  margin: 5px 0;
  color: #606266;
}
.user-bio {
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}
.user-info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.user-info-item i {
  margin-right: 10px;
  color: #409EFF;
}
.user-actions {
  padding-top: 20px;
  text-align: center;
}
.pagination-container {
  margin-top: 20px;
}
</style> 